package work.shyk.kongMonitor.dto.param;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.Data;
import utils.common.JsonUtils;
import work.shyk.kongMonitor.dto.param.interfaces.MustQuery;
import work.shyk.kongMonitor.dto.result.interfaces.ValueReceiver;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;

/**
 * description: <br>
 * createTime: 2021/3/24 14:49 <br>
 *
 * @author zzh
 */
@Data
public class EsAggsQuery {
    int size;

    @JsonProperty
    Map<String, Map<String, List<MustQuery>>> query;

    @JsonInclude(JsonInclude.Include.NON_NULL)
    Map<String, AbstractAggsQuery> aggs = new HashMap<>();


    public EsAggsQuery(List<MustQuery> list, List<AbstractAggsQuery> aggs) {
        query = new HashMap<>();
        Map<String, List<MustQuery>> temp = new HashMap<>();
        query.put("bool", temp);
        //Map<String, List<MustQuery>> tmp = new HashMap<>();
        temp.put("must", list);
        for (AbstractAggsQuery agg : aggs) {
            this.aggs.put(agg.getKey(), agg);
        }
    }

    public Object parse(String source, Supplier<ValueReceiver> receiverSupplier) throws IOException {
        Collection<AbstractAggsQuery> values = aggs.values();

        if(values.isEmpty()) {
            return null;
        }
        JsonNode jsonNode = JsonUtils.fromJson(source);
        ValueReceiver valueReceiver = receiverSupplier.get();
        for (AbstractAggsQuery value : values) {
            value.parse(jsonNode.get("aggregations"), () -> valueReceiver);
        }
        return valueReceiver;
    }
}
